package common

import (
	"errors"
	"strings"
)

// 截取url的根url
func GetRootUrl(url string) (string, error) {
	//获取url的根url   https://www.baidu.com

	//先跳过http:// 或者 https://
	//再找到第一个/的位置
	//截取到这个位置
	//返回
	isHttps := false
	if strings.HasPrefix(url, "https://") {
		isHttps = true
		url = strings.Replace(url, "https://", "", 1)
	} else if strings.HasPrefix(url, "http://") {
		url = strings.Replace(url, "http://", "", 1)
	} else if strings.HasPrefix(url, "//") {
		url = strings.Replace(url, "//", "", 1)
	} else {
		return "", errors.New("url格式不正确")
	}
	index := strings.Index(url, "/")
	if index == -1 {
		//拼接前缀
		if isHttps {
			return "https://" + url, nil
		} else {
			return "http://" + url, nil
		}
	} else {
		//拼接前缀
		if isHttps {
			return "https://" + url[:index], nil
		} else {
			return "http://" + url[:index], nil
		}
	}
}
